<?php

include_once './config.php';
include_once './Situare.php';
include_once './User.php';
include_once './display.php';

$action = isset($_GET['action']) ? $_GET['action'] : "";

if ($action == "") {       // no action? Show base page
    outputBasePage(false);
}

if ($action == "getusers") {
    outputUserList();
}

if ($action == "lastupdate") {
    getLastUpdate();
}

if ($action == "isconnected") {
    getIsConnected(true);
}

function getIsConnected($OutputNotReturn) {
    $situare = new Situare();
    $uid = $situare->getUID();

    if (!isset($uid) || $uid == "" || $uid < 100) {
        if ($OutputNotReturn == true) {
            echo "0";
        }
        else {
            return false;
        }
    }
    else {
        if ($OutputNotReturn == true) {
            echo "1";
        }
        else {
            return true;
        }
    }
}

function getLastUpdate() {
    $situare = new Situare();
    $user = $situare->getUser();

    header('Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    header('Pragma: no-cache');

    $friends = $user->getFriends();

    $lastUpdate = 0;                    // no update time

    foreach ($friends as $key => $friend) {
        if ($friend->fb_location) {    // if fb_location exists
            $thisUpdate = $friend->fb_location->timestamp;  // get this update time

            if ($thisUpdate > $lastUpdate) {   // if this update was later than last update
                $lastUpdate = $thisUpdate;
            }
        }
    }

    /*
      $outputData["lastupdate"] = $lastUpdate;
      echo json_encode($outputData);
     */
    echo $lastUpdate;
}

function outputUserList() {
    $situare = new Situare();
    $user = $situare->getUser();

    header('Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
    header('Pragma: no-cache');

    $friends = $user->getFriends();
    $friendsCount = count($friends);

    $userName = $user->fb_name;

    $users = array();
    $oneUser = array();

    foreach ($friends as $key => $friend) {
        $friendName = $friend->fb_name;
        $pic = $friend->fb_pic_url;

        if ($friend->fb_location) {    // if fb_location exists
            $locationStr = $friend->fb_location->address;
            $locationData = $friend->fb_location->data;
            $timestamp = $friend->fb_location->timestamp;
        } else {
            $locationStr = I18N::getMessage('location.unknown');
            $locationData = "";
            $timestamp = "";
        }

        if (empty($pic)) {
            $pic = DEFAULT_PROFILE_PHOTO_URL;
        }

        $oneUser["name"] = $friendName;
        $oneUser["picture"] = $pic;
        $oneUser["location"] = $locationStr;
        $oneUser["loctData"] = $locationData;
        $oneUser["timestamp"] = Display::epochToAgo($timestamp);

        $oneUser["distanceicon"] = Display::renderDistanceIconName($friend, $user);
        $oneUser["distancestring"] = Display::renderDistance($friend, $user);

        $users[$key] = $oneUser;
    }

    echo json_encode($users);
}

function locationLonLatToString($lon, $lat) {
    if (!isset($lon) || !isset($lat))
        return NULL;

    $queryUrl = "http://maps.google.com/maps/geo?q=$lon,$lat&output=csv&oe=utf8&sensor=false";

    $file = fopen($queryUrl, "r");
    $locArr = fgetcsv($file);
    fclose($file);

    if ($locArr[0] != 200)       // bad HTTP error code?
        return NULL;

    return $locArr[2];
}

function locationToString($location) {
    if (isset($location)) {
        $lon = $location->lon;
        $lat = $location->lat;

        $queryUrl = "http://maps.google.com/maps/geo?q=$lon,$lat&output=csv&oe=utf8&sensor=false";
        $reverseGeocode = file($queryUrl);
        $locationCSV = $reverseGeocode[0];

        $pos1 = strpos($locationCSV, ",", 0);

        $locationStr = "$lon, $lat";

        if ($pos1 != FALSE) {
            $pos2 = strpos($locationCSV, ",", $pos1 + 1);

            $locationString = substr($locationCSV, $pos2 + 1);

            $charFirst = $locationString[0];
            $charLast = $locationString[strlen($locationString) - 1];

            if ($charFirst == "\"" && $charLast == "\"") {
                $locationStr = substr($locationString, 1, strlen($locationString) - 2);
            }
        }
    } else {
        $locationStr = getMessage('location.unknown');
    }

    return $locationStr;
}

function outputBasePage($withoutHead) {
    $isConnected = getIsConnected(false);

    if ($isConnected == false) {
        echo "
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
    <title>Situare</title>
    <link href=\"resources/styles/list_view.css\" rel=\"stylesheet\" type=\"text/css\" />
    <link href=\"resources/styles/message_window.css\" rel=\"stylesheet\" type=\"text/css\" />
    <link href=\"resources/styles/details_window.css\" rel=\"stylesheet\" type=\"text/css\" />
    
    <meta http-equiv=\"refresh\" content=\"30; url=http://" . $_SERVER['SERVER_NAME'] . "/homescreen.php\" />
    
    <style type=\"text/css\">
        #homeScreenMessageLogo {
            width: 100%;
            height: 39px;
            background-image: url(resources/images/icon/situare_icon_new.png); 
            background-repeat: no-repeat;
            }
            
        #homeScreenMessageText {
            margin-left: 94px;
            text-align: center;
            }
            

        .infoBlockHome{
            background:url(resources/images/background/bg_blue_list.png);
            overflow:auto; 
            margin-left:0px;
            margin-right:0px;
            margin-top:0px;
            -moz-border-radius: 5px;
            -webkit-border-radius: 5px;
            position: relative;
            }
            
    </style>		

</head>
<body>

    <div id=\"homeScreenMessage\" class=\"infoBlockHome\">
        <div id=\"homeScreenMessageLogo\">
            <div id=\"homeScreenMessageText\">
                <font face=\"Verdana\">Connecting...</font>
            </div>
        </div>
    </div>
    
</body>
</html>
";

        return;
    }

    $situare = new Situare();
    $user = $situare->getUser();

    if ($withoutHead == false) {
        header('Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
        header('Pragma: no-cache');

        echo "
<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
    <title>Situare</title>
    <link href=\"resources/styles/list_view.css\" rel=\"stylesheet\" type=\"text/css\" />
    <link href=\"resources/styles/message_window.css\" rel=\"stylesheet\" type=\"text/css\" />
    <link href=\"resources/styles/details_window.css\" rel=\"stylesheet\" type=\"text/css\" />
    
    <meta http-equiv=\"refresh\" content=\"300; url=http://" . $_SERVER['SERVER_NAME'] . "/homescreen.php\" />
</head>
<body>";
    }

    echo "
<div class=\"infoBlock\" id=\"homeScreenDiv\">
    <div class=\"photoArea\">
        <img id=\"userPict\" src=\"\" />
    </div>
        
    <div class=\"texArea\">
        <table class=\"tableIDinfo\" cellspacing=\"0\" cellpadding=\"0\">
            <tr>
                <td colspan=\"2\" class=\"IDname\"> <span id=\"userName\"> </span> </td>
            </tr>
            <tr>
                <td colspan=\"2\" class=\"separatorID\"></td>
            </tr>
            <tr>
                <td class=\"iconID\"><img src=\"resources/images/icon/list_small.png\"/></td>
                <td class=\"infoID\"><span id=\"locationData\"> </span> </td>
            </tr>
            <tr>
                <td class=\"iconID\"><img src=\"resources/images/icon/compas_small.png'\"/></td>
                <td class=\"infoID\"><span id=\"locationAddress\"> </span> </td>
            </tr>
            <tr>
                <td class=\"iconID\"><img src=\"resources/images/icon/clock_small.png\"/></td>
                <td class=\"infoID\"><span id=\"timeEpoch\"> </span></td>
            </tr>
            <tr>
                <td colspan=\"2\" class=\"emptyID\"></td>
            </tr>
        </table>
    </div>
        
    <div class=\"moreInfoArea\">
        <div class=\"distanceInfo\" id=\"distance\">
        </div>
        
        <div class=\"mapInfo\" >
            <!--
                <img src=\"' . getResource('images/icon/info_icon.png') . '\" style=\"opacity:0.6;filter:alpha(opacity=60)\" onmouseover=\"this.style.opacity=1;this.filters.alpha.opacity=100\" onmouseout=\"this.style.opacity=0.6;this.filters.alpha.opacity=60\" />
            -->
        </div>
    </div>      
</div>      

<span id=\"debugDiv\"> </span>

<!--  ============================================================== -->

<script type=\"text/javascript\">

    var counter = 0;";

    $friends = $user->getFriends();

    echo "\nvar friends = new Array(" . implode(',', array_keys($friends)) . ");";





    echo "
    var friendNames             = new Array();
    var friendPicts             = new Array();
    var friendImags             = new Array();
    var friendLocts             = new Array();
    var friendLocData           = new Array();
    var friendLocTime           = new Array();
    var friendDistanceImage     = new Array();
    var friendDistanceString    = new Array();

    var friendsCount = 0; 
    var lastUpdate = 0;
    var otherCounter = 0;

    initUserList();                 // the initial user list
    switchUser();

    setInterval(\"switchUser()\", 5000);

function switchUser()
{
    var spanName            = document.getElementById('userName');
    var imgUser             = document.getElementById('userPict');
    var spanLocationData    = document.getElementById('locationData');
    var spanLocationAddress = document.getElementById('locationAddress');
    var spanTimeEpoch       = document.getElementById('timeEpoch');
//    var imgDistance         = document.getElementById('distanceIcon');
//    var spanDistanceString  = document.getElementById('distanceString');
    var divDistance         = document.getElementById('distance');

    spanName.innerHTML              = friendNames[friends[counter]];
    imgUser.src                     = friendPicts[friends[counter]];
    spanLocationData.innerHTML      = friendLocData[friends[counter]];
    spanLocationAddress.innerHTML   = friendLocts[friends[counter]];
    spanTimeEpoch.innerHTML         = friendLocTime[friends[counter]];
//    imgDistance.src                 = friendDistanceImage[friends[counter]];
//    spanDistanceString              = friendDistanceString[friends[counter]];

    divDistance.innerHTML = '<img src=\"' + friendDistanceImage[friends[counter]] + '\"> ' + friendDistanceString[friends[counter]];

    if(counter < (friendsCount - 1))
        counter++;
    else
        counter = 0;
}

function initUserList()
{
";

    $friends = $user->getFriends();
    $friendsCount = count($friends);

    echo "friendsCount = $friendsCount; \n";

    $userName = $user->fb_name;
    $lastUpdate = 0;                    // no update time

    foreach ($friends as $key => $friend) {
        $friendName = $friend->fb_name;
        $pic = $friend->fb_pic_url;

        if ($friend->fb_location) {    // if fb_location exists
            $locationStr = $friend->fb_location->address;
            $locationData = $friend->fb_location->data;
            $timestamp = $friend->fb_location->timestamp;
        } else {
            $locationStr = I18N::getMessage('location.unknown');
            $locationData = "";
            $timestamp = "";
        }

        $distanceString = Display::renderDistance($friend, $user);

        $distanceImage = Display::renderDistanceIconFileName($friend, $user);

        if ($distanceImage == "") {
            $distanceImage = "./resources/images/icon/info/walk_icon_gray.png";
        }

        if (empty($pic)) {
            $pic = DEFAULT_PROFILE_PHOTO_URL;
        }

        $epochString = Display::epochToAgo($timestamp);

        echo "
        friendNames[$key] = \"$friendName\"; 
        friendPicts[$key] = \"$pic\"; 
        friendLocts[$key] = \"$locationStr\";
    	friendLocData[$key] = \"$locationData\";
        friendLocTime[$key] = \"$epochString\";

        friendDistanceImage[$key] = \"$distanceImage\";
        friendDistanceString[$key] = \"$distanceString\";
        ";
    }

    echo "\n\n lastUpdate = $lastUpdate; \n} \n\n </script>";

    if ($withoutHead == false) {
        echo "</body> </html>";
    }
}

?>
